package com.renjian.screens;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.container.MainScreen;

import com.renjian.model.KeyMap;
import com.renjian.model.Status;
import com.renjian.util.Constant;
import com.renjian.util.HttpConnectionUtil;

public class UserTimeLineScreen extends MainScreen implements Constant {

	public UserTimeLineScreen() {
		try {
			setUi();
		} catch (IOException e) {
			logger.log(e.getMessage());
		}
	}

	private void setUi() throws IOException {
		String username = _resource.getString(USERNAME).trim();
		String password = _resource.getString(PASSWORD).trim();
		String auth = hack.base64Encrypt(username + ":" + password);
		KeyMap[] paras = new KeyMap[4];// page=1&since_id=361379&count=2
		KeyMap[] keyMap = new KeyMap[5];
		paras[0] = new KeyMap();
		paras[0].setKey("page");
		paras[0].setVal("1");

		paras[1] = new KeyMap();
		paras[1].setKey("since_id");
		paras[1].setVal("0");

		paras[2] = new KeyMap();
		paras[2].setKey("count");
		paras[2].setVal("2");

		paras[3] = new KeyMap();
		paras[3].setKey("max_id");
		paras[3].setVal("99999999");

		keyMap[0] = new KeyMap();
		keyMap[0].setKey("Authorization");
		keyMap[0].setVal("Basic " + auth);

		keyMap[1] = new KeyMap();
		keyMap[1].setKey("page");
		keyMap[1].setVal("1");

		keyMap[2] = new KeyMap();
		keyMap[2].setKey("since_id");
		keyMap[2].setVal("0");

		keyMap[3] = new KeyMap();
		keyMap[3].setKey("max_id");
		keyMap[3].setVal("99999999");

		keyMap[4] = new KeyMap();
		keyMap[4].setKey("count");
		keyMap[4].setVal("2");

		String url = _resource.getString(USER_TIMELINE);
		try {
			new HttpConnectionUtil() {

				public boolean process(byte[] ch) {
					String ret = null;
					try {
						ret = new String(ch, "utf-8");
						try {
							Status[] stas = new Status().xmlToStatusArray(ret);
							logger.log(stas.toString());
							add(new RichTextField(stas.toString()));
						} catch (Exception e) {
							logger.log(e.getMessage());
						}
					} catch (UnsupportedEncodingException e) {
						logger.log(e.getMessage());
					}
					logger.log("hpx success:" + ret);

					return true;
				}

			}.processRequest(url, paras, keyMap);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
